<template>
  <VBaseDialog
    @close="handleClose"
    @save="save"
    :loading="loading"
    width="950"
    destroy-on-close
  >
    <template #content>
      <div>
        <el-form
          label-position="top"
          ref="formRef"
          :model="formValues"
          :rules="rules"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="运输类型" prop="transport_type">
                <el-select
                  v-model="formValues.transport_type"
                  placeholder="请选择"
                  class="w-full"
                  filterable
                  :disabled="isEdit"
                >
                  <el-option
                    v-for="item in option?.transport_type || []"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配置类型" prop="config_type">
                <el-select
                  v-model="formValues.config_type"
                  placeholder="请选择"
                  class="w-full"
                  @change="handleConfigType"
                  :disabled="isEdit"
                >
                  <el-option
                    v-for="item in option?.tc_time_config_type || []"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="类型" prop="wp_type">
                <el-select
                  v-model="formValues.wp_type"
                  placeholder="请选择"
                  class="w-full"
                  @change="handleWpType"
                  :disabled="isEdit"
                >
                  <el-option
                    v-for="item in option?.wp_type || []"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <template v-if="formValues.config_type == 1">
                <el-form-item label="仓点" prop="wp_ids">
                  <el-select
                    v-model="formValues.wp_ids"
                    placeholder="请选择"
                    class="w-full"
                    filterable
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                  >
                    <el-option
                      v-for="item in warehouseData"
                      :key="item.value"
                      :label="item.wp_full_name"
                      :value="item.wp_id"
                    />
                  </el-select>
                </el-form-item>
              </template>
              <template v-else>
                <el-form-item label="国家" prop="country_code">
                  <el-select
                    v-model="formValues.country_code"
                    placeholder="请选择"
                    class="w-full"
                    multiple
                    collapse-tags
                    filterable
                    collapse-tags-tooltip
                    :disabled="isEdit"
                  >
                    <el-option
                      v-for="item in option?.country || []"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-col>
          </el-row>

          <el-form-item label="渠道" v-if="props.type == 2">
            <el-select
              v-model="formValues.channel_id"
              placeholder="请选择"
              class="w-full"
              filterable
              clearable
            >
              <el-option
                v-for="item in option?.channel || []"
                :key="item.channel_id"
                :label="item.channel_name"
                :value="item.channel_id"
              />
            </el-select>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="Shipmentid有效期">
                <el-input-number
                  v-model="formValues.days_shipmentid_validity"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发货-开船(平均)">
                <el-input-number
                  v-model="formValues.days_to_departure"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开船-到港(平均)">
                <el-input-number
                  v-model="formValues.days_to_arrival"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到港-清关(平均)">
                <el-input-number
                  v-model="formValues.days_to_customs_clearance"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="清关-提取(平均)">
                <el-input-number
                  v-model="formValues.days_to_pickup"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="提取-签收(平均)">
                <el-input-number
                  v-model="formValues.days_to_receipt"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="签收-上架(第一次)(平均)">
                <el-input-number
                  v-model="formValues.days_to_first_shelving"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="上架(第一次)-上架完成(平均)">
                <el-input-number
                  v-model="formValues.days_to_full_shelving"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出口查验(平均)">
                <el-input-number
                  v-model="formValues.days_export_inspection"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="进口查验(平均)">
                <el-input-number
                  v-model="formValues.days_import_inspection"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="签收差异提醒天数(平均)">
                <el-input-number
                  v-model="formValues.days_receipt_variance_alert"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上架差异提醒天数(平均)">
                <el-input-number
                  v-model="formValues.days_shelving_variance_alert"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发货-开船(标准)">
                <el-input-number
                  v-model="formValues.days_to_departure_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开船-到港(标准)">
                <el-input-number
                  v-model="formValues.days_to_arrival_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到港-清关(标准)">
                <el-input-number
                  v-model="formValues.days_to_customs_clearance_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="清关-提取(标准)">
                <el-input-number
                  v-model="formValues.days_to_pickup_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="提取-签收(标准)">
                <el-input-number
                  v-model="formValues.days_to_receipt_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="签收-上架(第一次)(标准)">
                <el-input-number
                  v-model="formValues.days_to_first_shelving_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="上架(第一次)-上架完成(标准)">
                <el-input-number
                  v-model="formValues.days_to_full_shelving_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出口查验(标准)">
                <el-input-number
                  v-model="formValues.days_export_inspection_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="进口查验(标准)">
                <el-input-number
                  v-model="formValues.days_import_inspection_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="签收差异提醒天数(标准)">
                <el-input-number
                  v-model="formValues.days_receipt_variance_alert_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上架差异提醒天数(标准)">
                <el-input-number
                  v-model="formValues.days_shelving_variance_alert_standard"
                  :controls="false"
                  placeholder="请输入"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="截单日期">
            <div
              v-for="(item, index) in formValues.cut_off_date"
              :key="item"
              class="mb-[8px]"
            >
              <VGroup>
                <el-select
                  v-model="item.week"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="it in week"
                    :key="it.value"
                    :label="it.label"
                    :value="it.value"
                  />
                </el-select>
                <el-select
                  v-model="item.hour"
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="it in time"
                    :key="it.value"
                    :label="it.label"
                    :value="it.value"
                  />
                </el-select>
                <div class="ml-[16px]">
                  <span
                    class="hover:text-[#2080f0] cursor-pointer mr-[8px]"
                    @click="handleAdd(index)"
                  >
                    <SvgIcon icon-class="Plus" class="text-[12px] inline" />
                  </span>
                  <span
                    class="hover:text-[#2080f0] cursor-pointer"
                    @click="handleDelete(index)"
                    v-if="formValues.cut_off_date.length > 1"
                    ><SvgIcon icon-class="Minus" class="text-[12px] inline" />
                  </span>
                </div>
              </VGroup>
            </div>
          </el-form-item>
          <el-col :span="6">
            <el-form-item label="轨迹维护天数">
              <el-input-number
                v-model="formValues.track_maintain_days"
                :controls="false"
                placeholder="请输入"
                class="w-full"
              />
            </el-form-item>
          </el-col>
        </el-form>
      </div>
    </template>
  </VBaseDialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import SvgIcon from "@/components/SvgIcon/index.vue";
import {
  preTimeConfigUpdate,
  preTimeConfigCreate,
  preTimeConfigDetail,
} from "../api";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  type: { type: [String, Number], default: "" },
  option: { type: Object, default: () => {} },
});
const { option } = toRefs(props);
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const formValues = ref({
  wp_ids: [],
  cut_off_date: [{ week: null, hour: null }],
  country_code: [],
});
const rules = reactive({
  transport_type: [
    { required: true, message: "请选择运输类型", trigger: "change" },
  ],
  wp_type: [{ required: true, message: "请选择类型", trigger: "change" }],
  wp_ids: [{ required: true, message: "请选择仓点", trigger: "change" }],
  config_type: [
    { required: true, message: "请选择配置类型", trigger: "change" },
  ],
  country_code: [{ required: true, message: "请选择国家", trigger: "change" }],
});
const formRef = ref();
const warehouseData = computed(() => {
  if (!formValues.value?.wp_type) return [];
  let wp_type_data = option.value?.wp_type.findIndex(
    (item) => item.value == formValues.value.wp_type
  );
  let arr = option.value?.wp_type[wp_type_data].wp;
  return arr;
});
watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);
const getDetail = async (val) => {
  const { data } = await preTimeConfigDetail({ id: val });
  formValues.value = data || {};
  // formValues.value.cut_off_date = (data?.cut_off_date || []).map(([w, t]) => ({
  //   w,
  //   t,
  // }));
  if (!formValues.value?.cut_off_date?.length) {
    formValues.value.cut_off_date.push({ week: null, hour: null });
  }
};
const handleWpType = (val) => {
  formValues.value.wp_ids = [];
};
const isEdit = computed(() => {
  return !!props.id;
});
const week = computed(() =>
  Array.from({ length: 7 }, (_, i) => ({
    label: `星期${["一", "二", "三", "四", "五", "六", "日"][i]}`,
    value: i,
  }))
);

// 动态生成时间数据
const time = computed(() =>
  Array.from({ length: 24 }, (_, i) => ({
    label: `${i}点`,
    value: i,
  }))
);
const handleConfigType = (val) => {
  formValues.value.wp_ids = [];
  formValues.value.country_code = [];
};
const handleAdd = (index) => {
  formValues.value.cut_off_date.splice(index + 1, 0, {
    week: null,
    hour: null,
  });
};
const handleDelete = (index) => {
  formValues.value.cut_off_date.splice(index, 1);
};
const save = () => {
  try {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const payload = {
          ...formValues.value,
        };
        const { code, message } = await (isEdit.value
          ? preTimeConfigUpdate
          : preTimeConfigCreate)(payload);
        if (code != 200) return ElMessage.error(message);
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } else {
        return false;
      }
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  formValues.value = {
    wp_ids: [],
    country_code: [],
    cut_off_date: [{ w: null, t: null }],
  };
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
